import 'package:flutter/material.dart';
import 'package:get/get.dart';

import '../../../../common/models/enums/index.dart';
import '../../../../common/services/index.dart';
import '../../../../common/style/index.dart';
import '../../../../common/utils/index.dart';

class SkinController extends GetxController {
  SkinController();

  Rx<ThemeMode> themeMode = Rx<ThemeMode>(ThemeMode.system);
  Rx<O2Skin> skin = O2Skin.blue.obs;

  _initData() {
    update(["skin"]);
  }
 
  @override
  void onReady() {
    loadThemeMode();
    super.onReady();
  }

  Future<void> loadThemeMode() async {
    final mode = SharedPreferenceService.to.getString(SharedPreferenceService.appThemeModeKey);
    OLogger.d('存储的mode： $mode');
    if (mode.isEmpty) {
      themeMode.value = ThemeMode.system; // 默认跟随系统
    } else {
      if (mode == ThemeMode.light.name) {
        themeMode.value = ThemeMode.light;
      } else if (mode == ThemeMode.dark.name) {
        themeMode.value = ThemeMode.dark;
      } else {
        themeMode.value = ThemeMode.system;
      }
    }
    OLogger.d('当前主题mode ：${themeMode.value.name}');

    final skinName = SharedPreferenceService.to
        .getString(SharedPreferenceService.appThemeSkinKey);
    var s = O2Skin.blue;
    if (skinName.isNotEmpty) {
      s = AppTheme.getSkinByName(skinName);
    }
    skin.value = s;
    
    _initData();
  }
 

  Future<void> changeWithSystem(bool value) async {
    OLogger.d('切换跟随系统，$value');
    if (value) {
      themeMode.value = ThemeMode.system; // 默认跟随系统
    } else {
      themeMode.value = ThemeMode.light;
    }
    _initData();
    updateUI();
  }
  Future<void> clickLightMode() async {
    if (themeMode.value == ThemeMode.light) {
      return;
    }
    themeMode.value = ThemeMode.light;
    _initData();
    updateUI();
  }
  Future<void> clickDarkMode() async {
    if (themeMode.value == ThemeMode.dark) {
      return;
    }
    themeMode.value = ThemeMode.dark;
    _initData();
    updateUI();
  }

  Future<void> updateUI() async {
    await SharedPreferenceService.to.putString(SharedPreferenceService.appThemeModeKey, themeMode.value.name);
    Get.changeThemeMode(themeMode.value);
    OLogger.d('切换模式');
  }

  /// 点击切换主题皮肤
  clickChangeSkin(O2Skin s) {
    if (skin.value == s) {
      return;
    }
    skin.value = s;
    _initData();
    updateSkin();
  }

  /// 切换主题皮肤
  Future<void> updateSkin() async {
    await SharedPreferenceService.to.putString(SharedPreferenceService.appThemeSkinKey, skin.value.name);
    final theme = Get.isDarkMode ? AppTheme.getDarkThemeBySkin(skin.value) :  AppTheme.getLightThemeBySkin(skin.value);
    Get.changeTheme(theme);
  }

}
